import React, { PureComponent } from 'react';
import { Tabs, Button, Table, Divider, Modal, Form, Input, notification, Select, Row, Col, message, Icon, Upload } from 'antd';
import '@/assets/css/store.scss';
import * as APIService from '../../axios/api_ln';
import ReactHTMLTableToExcel from 'react-html-table-to-excel';
import ReactDOM from 'react-dom';
const { TabPane } = Tabs;
const { Option } = Select;
const { confirm } = Modal;
const FormItem = Form.Item;


// //弹出通知提醒框
function openNotification(type, message) {
  notification.open({
    type: type,
    message: message,
    duration: 2,
  });
};

class App extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      loading: false, //加载中...
      dataSource: [],
      visible: false, //显示与隐藏
      modalData: '',//选中的数据
      handleType: 0,//新增0 修改1
      id: 0, //主键id
      selectedRowKeys: [], //可选择表格
      fileList: [],//存放上传信息：比如路径、文件名
      imgList: [],//存放回显信息：修改时的路径、文件名
      columns: [
        {
          dataIndex: '',
          width: '80px'
        },
  
        {
          title: '序号',
          width: '10%',
          render: (text, record, index) => `${index + 1}`,
        },
        {
          title: '物料编码',
          dataIndex: 'matterCod',
        },
        {
          title: '供应商编码',
          dataIndex: 'supplierCode',
        },
        {
          title: '库龄',
          dataIndex: 'stockAge',
        },
        {
          title: '最低库存',
          dataIndex: 'minimumStock',
        },
        {
          title: '最高库存',
          dataIndex: 'maximumStock',
        },
        {
          title: '呆滞时间',
          dataIndex: 'dullnessTime',
        },
        {
          title: '交货订单处理时间',
          dataIndex: 'deliveryOrderTime',
        },
        {
          title: '收货货品上架处理时间',
          dataIndex: 'receiptTime',
        },
        {
          title: '补货任务处理时间',
          dataIndex: 'replenishmentTaskTime	',
        },
        {
          title: '操作',
          width: '12%',
          render: (text, record) => {
            return <span>
              <a onClick={() => this.showModal(record, 1)}>修改</a>
              <Divider type="vertical" />
              <a onClick={() => this.showDeleteConfirm(record, 2)}>
                删除
              </a>
            </span>
          }
        }
      ]
    };
}


  componentDidMount() {
    this.fetch();
      const tableCon = ReactDOM.findDOMNode(this.refs['table']); // 通过ref属性找到该table
      const table = tableCon.querySelector('table');  //获取table
      table.setAttribute('id','table-to-xls')     //给该table设置属性
    
  }

  //初始化加载数据
  fetch = (str) => {
    this.setState({ loading: true })
    APIService.list().then(data => {
      //console.log(data.data.data)
      const dataSource = data.data.data;
      this.setState({
        dataSource: dataSource,
        loading: false,
      })
    })
  }

  handleChangeTab = key => { };

  //添加修改 提交
  submitMenu = (e) => {
    this.props.form.validateFields(['matterCod', 'supplierCode', 'stockAge', 'deliveryOrderTime', 'dullnessTime', 'maximumStock', 'minimumStock', 'receiptTime', 'replenishmentTaskTime'], (err, values) => {
      console.log(values)
      if (!err) {
        if (this.state.handleType === 0) {
          values = Object.assign({}, values, {})
          APIService.addWarningManagement(values).then(data => {
            if (data.data.code === 200) {
              openNotification('success', '操作成功')
            } else {
              openNotification('warning', data.data.msg)
            }
            that.handleCancel();
            that.props.form.resetFields();
            that.fetch();
          })
        } else {
          values = Object.assign({}, values, { id: this.state.id })
          APIService.updateWarningManagement(values).then(data => {
            if (data.data.code === 200) {
              openNotification('success', '操作成功')
            } else {
              openNotification('warning', data.data.msg)
            }
            that.handleCancel();
            that.props.form.resetFields();
            that.fetch();
          })
        }
        const that = this;
      } else {
        console.log(err);
      }
    });
  }


  //弹出删除框
  showDeleteConfirm = (data, type) => {
    const that = this;
    confirm({
      title: '确认删除' + '[' + data.matterCod + ']？',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        if (type === 2) {
          APIService.deleteWarningManagement(data.id).then(data => {
            openNotification('success', '删除成功');
            that.fetch();
          }).catch(function (error) {
            openNotification('error', error.message);
          });
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  onExpand = (record, index, indent, expanded) => { }

  //0新增  1修改
  showModal = (data, type) => {
    const that = this;
    if (type === 1) {
      this.props.form.setFieldsValue({
        deliveryOrderTime: data.deliveryOrderTime,
        dullnessTime: data.dullnessTime,
        matterCod: data.matterCod,
        maximumStock: data.maximumStock,
        minimumStock: data.minimumStock,
        receiptTime: data.receiptTime,
        replenishmentTaskTime: data.replenishmentTaskTime,
        stockAge: data.stockAge,
        supplierCode: data.supplierCode,
      })
    }

    this.setState({
      visible: true,
      modalData: data,
      handleType: type,
      id: data.id,
    });
  };

  handleCancel = e => {
    this.props.form.resetFields();//清除form表单控件的值
    this.setState({
      visible: false,
    });
  };

  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  //form表单提交事件
  handleSubmit = e => {
    const { dispatch, form } = this.props;
    e.preventDefault();
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { imgList } = this.state
        values.imgList = JSON.stringify(imgList);
        console.log('values', values);
      }
    });
  };


  //开始模板下载
  // async
  dowmloadQuery = (data) => {
    window.open('http://192.168.10.24:9003/gd-wms-base/warningManagement/excelTemplateDownload')
    // const res = await downloadQuery(data);
    // //type：'application/.....'这里是xlsx的类型
    // let blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    // if (window.navigator.msSaveOrOpenBlob) {
    //   navigator.msSaveBlob(blob, res.fileName)
    // } else {
    //   let downloadElement = document.createElement('a');
    //   let href = window.URL.createObjectURL(blob); // 创建下载的链接
    //   downloadElement.href = href;
    //   downloadElement.download = res.fileName; // 下载后文件名
    //   document.body.appendChild(downloadElement);
    //   downloadElement.click(); // 点击下载
    //   document.body.removeChild(downloadElement); // 下载完成移除元素
    //   window.URL.revokeObjectURL(href); // 释放掉blob对象
    // }
    APIService.excelTemplateDownload(data).then(data => {
      console.log(data.data.data)
      openNotification('success', '下载成功');
      // that.fetch('');
    })
  };


  // //下载模版
  // downloadExl = (json, type) => {
  //   var tmpdata = json[0];
  //   json.unshift({});
  //   var keyMap = []; //获取keys
  //   for (var k in tmpdata) {
  //     keyMap.push(k);
  //     json[0][k] = k;
  //   }
  //   var tmpdata = [];//用来保存转换好的json 
  //   json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
  //     v: v[k],
  //     position: (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
  //   }))).reduce((prev, next) => prev.concat(next)).forEach((v, i) => tmpdata[v.position] = {
  //     v: v.v
  //   });
  //   var outputPos = Object.keys(tmpdata); //设置区域,比如表格从A1到D10
  //   var tmpWB = {
  //     SheetNames: ['mySheet'], //保存的表标题
  //     Sheets: {
  //       'mySheet': Object.assign({},
  //         tmpdata, //内容
  //         {
  //           '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] //设置填充区域
  //         })
  //     }
  //   };
  //   tmpDown = new Blob([this.s2ab(XLSX.write(tmpWB,
  //     { bookType: (type == undefined ? 'xlsx' : type), bookSST: false, type: 'binary' }//这里的数据是用来定义导出的格式类型
  //   ))], {
  //     type: ""
  //   }); //创建二进制对象写入转换好的字节流
  //   var href = URL.createObjectURL(tmpDown); //创建对象超链接
  //   this.state.href = href;
  //   setTimeout(function () { //延时释放
  //     URL.revokeObjectURL(tmpDown); //用URL.revokeObjectURL()来释放这个object URL
  //   }, 100);
  // }
  // s2ab = (s) => { //字符串转字符流
  //   var buf = new ArrayBuffer(s.length);
  //   var view = new Uint8Array(buf);
  //   for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  //   return buf;
  // }
  // // 将指定的自然数转换为26进制表示。映射关系：[0-25] -> [A-Z]。
  // getCharCol = (n) => {
  //   let temCol = '',
  //     s = '',
  //     m = 0
  //   while (n > 0) {
  //     m = n % 26 + 1
  //     s = String.fromCharCode(m + 64) + s
  //     n = (n - m) / 26
  //   }
  //   return s
  // }

 

  handleSearch = (e) => {
    this.props.form.validateFields(['Code', 'supplierCod'], (err, values) => {
      var str = '';
      if (values.Code !== undefined) {
        str += 'matterCod=' + values.Code;
      }
      if (values.supplierCod !== undefined) {
        str += 'supplierCode=' + values.supplierCod;
      }
      APIService.param(str).then(data => {
        const dataSource = data.data.data;
        console.log(dataSource)
        this.setState({
          dataSource: dataSource
        })
      })
    });
  };

  render() {
    //上传文件
    const props = {
      name: 'file',
      action: 'http://192.168.10.24:9003/gd-wms-base/warningManagement/excel/importExcel',
      accept: '.doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.xls',
      headers: {
        Token: localStorage.getItem('token'),
        // authorization: 'authorization-text',
      },
      onChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          message.success(`${info.file.name} file uploaded successfully`);
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} file upload failed.`);
        }
      },
    };

    const { getFieldDecorator } = this.props.form;
    const pStyle = {
      fontSize: 16,
      color: 'rgba(0,0,0,0.85)',
      lineHeight: '24px',
      display: 'block',
      marginBottom: 16,
      fontWeight: 700,
    };

    //设置表单的排布--类栅格
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 30
        },
        sm: {
          span: 10
        },
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 14
        },
      },
    };

    const { loading, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;

    const formItemLayout_addMenu = {
      labelCol: {
        sm: { span: 8 }
      },
      wrapperCol: {
        sm: { span: 9 }
      }
    };

    const { fileList } = this.state
    // const props = {
    //   name: 'UploadFile',//name得看接口需求，name与接口需要的name一致
    //   action: 'http://192.168.31.49:9998/warningManagement/excelTemplateDownload',//接口路径
    //   data: {},//接口需要的参数，无参数可以不写
    //   multiple: true,//支持多个文件
    //   showUploadList: true,//展示文件列表
    // }



    // 新增按钮
    var operations = <div className="mydiv" >
      {/* <div className='btnDiv'> */}
      < Button onClick={() => { this.showModal([], 0) }} type='primary'> <Icon type="plus" /> 新增</Button>
      {/* < Button onClick={this.dowmloadQuery} type='primary'> <Icon type="download" /> 模板下载</Button> */}
      < Button type='primary'> <Icon type="download" />
      <ReactHTMLTableToExcel
                    id="test-table-xls-button"
                    className="download-table-xls-button"
                    table="table-to-xls"
                    filename="文件名称" 
                    sheet="预警管理信息模板"
                    buttonText="导出"/></Button>
      
      <Upload {...props}>
        <Button type="primary">
          <Icon type="upload" /> 导入
        </Button>
      </Upload>
      
      {/* </div > */}
    </div >

    return (
      <div className="shadow-radius">
        <Form className="search-form" style={{ paddingBottom: 0 }}>
          <Row gutter={24}>
            <Col span={4}>
              <FormItem label="物料编码">
                {getFieldDecorator('Code')(
                  <Input placeholder='请输入物料编码' />
                )}
              </FormItem>
            </Col>
            <Col span={4}>
              <FormItem label="供应商编码">
                {getFieldDecorator('supplierCod')(
                  <Input placeholder='请输入供应商编码' />
                )}
              </FormItem>
            </Col>
            <Col span={2} style={{ marginRight: '10px', display: 'flex' }} className="serarch-btns">
              <FormItem>
                <Button icon="search" type="primary" htmlType="submit" className={'btn'} onClick={this.handleSearch}>
                  查询
								</Button>
              </FormItem>
            </Col>
          </Row>
        </Form>

        {/* <Table rowSelection={rowSelection} columns={this.state.columns} dataSource={this.state.dataSource} pagination={this.state.pagination} loading={this.state.loading} onExpand={(expanded, record) => this.onExpand(expanded, record)} rowKey={(record) => record.id} tabBarExtraContent={operations} /> */}

        <Tabs tabBarExtraContent={operations} defaultActiveKey="1" onChange={this.handleChangeTab}>
          <TabPane tab="预警信息管理" key="1">
            <Table columns={this.state.columns} rowKey={(record) => record.id} dataSource={this.state.dataSource} pagination={false} loading={this.state.loading} onExpand={(expanded, record) => this.onExpand(expanded, record)} ref={'table'} />
          </TabPane>
        </Tabs>

        <Modal
          width='600px'
          title="新增/修改"
          visible={this.state.visible}
          centered
          onOk={this.submitMenu}
          onCancel={this.handleCancel}
          okText="保存"
          cancelText="取消"
        >
          <Form {...formItemLayout_addMenu}>
            <Form.Item label="物料编码">
              {getFieldDecorator('matterCod', {
                rules: [{ required: true, message: '请填写物料id！' }]
              })(<Input placeholder="请填写物料编码" />)}
            </Form.Item>
            <Form.Item label="供应商编码">
              {getFieldDecorator('supplierCode', {
                rules: [{ required: true, message: '请填写供应商编码！' }]
              })(<Input placeholder="请填写供应商编码" />)}
            </Form.Item>
            <Form.Item label="库龄">
              {getFieldDecorator('stockAge', {})(<Input placeholder="请填写库龄" />)}
            </Form.Item>
            <Form.Item label="最低库存">
              {getFieldDecorator('minimumStock', {})(<Input placeholder="请填写最低库存" />)}
            </Form.Item>
            <Form.Item label="最高库存">
              {getFieldDecorator('maximumStock', {})(<Input placeholder="请填写最高库存" />)}
            </Form.Item>
            <Form.Item label="呆滞时间">
              {getFieldDecorator('dullnessTime', {})(<Input placeholder="请填写呆滞时间" />)}
            </Form.Item>
            <Form.Item label="交货订单处理时间">
              {getFieldDecorator('deliveryOrderTime', {})(<Input placeholder="请填写交货订单处理时间" />)}
            </Form.Item>
            <Form.Item label="收货货品上架处理时间">
              {getFieldDecorator('receiptTime', {})(<Input placeholder="请填写收货货品上架处理时间" />)}
            </Form.Item>
            <Form.Item label="补货任务处理时间">
              {getFieldDecorator('replenishmentTaskTime', {})(<Input placeholder="请填写补货任务处理时间" />)}
            </Form.Item>
          </Form>
        </Modal>

      </div>
    );
  }
}
export default Form.create()(App);
